package com.mkbk.service.impl;

import com.mkbk.mapper.ComponentMapper;
import com.mkbk.model.Component;
import com.mkbk.service.ComponentService;
import com.mkbk.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ComponentServiceImpl implements ComponentService {
    ComponentMapper componentMapper;

    // 获取所有的零件
    @Override
    public List<Component> getAllComponent(Component component) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        componentMapper = sqlSession.getMapper(ComponentMapper.class);
        List<Component> componentList = componentMapper.getAllComponent(component.getcName());
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
        return componentList;
    }

    // 分页查询
    @Override
    public List<Component> getAllComponentByPage(Component component, int current, int pageSize) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        componentMapper = sqlSession.getMapper(ComponentMapper.class);
        List<Component> componentList = componentMapper.getAllComponentByPage(component.getcName(), current, pageSize);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
        return componentList;
    }

    // 添加零件
    @Override
    public void addComponent(Component component) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        componentMapper = sqlSession.getMapper(ComponentMapper.class);
        componentMapper.addComponent(component);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    // 删除零件
    @Override
    public void deleteComponentById(int id) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        componentMapper = sqlSession.getMapper(ComponentMapper.class);
        componentMapper.deleteComponentById(id);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    // 修改零件
    @Override
    public void updateComponentById(Component component) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        componentMapper = sqlSession.getMapper(ComponentMapper.class);
        componentMapper.updateComponentById(component);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    // 查询详情
    @Override
    public Component getComponentById(int id) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        componentMapper = sqlSession.getMapper(ComponentMapper.class);
        Component component = componentMapper.getComponentById(id);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
        return component;
    }
}
